package com.ruizhong.centercontroll;

import android.media.projection.MediaProjection;
import android.util.Log;

import java.util.concurrent.LinkedBlockingQueue;

public class ScreenLive extends Thread {
    //    rtmp://127.0.0.1/live/livestream
    private String url;
    private MediaProjection mediaProjection;
    private LinkedBlockingQueue<RTMPPackage> queue = new LinkedBlockingQueue<>();

    private boolean isLiving;

    static {
        System.loadLibrary("pushStream");
    }

    private native boolean connect(String url);

    private native boolean sendData(byte[] data, int len, long tms, int type);

    public void addPackage(RTMPPackage rtmpPackage) {
        if (!isLiving) {
            return;
        }
        queue.add(rtmpPackage);
    }

    public void startLive(String url, MediaProjection mediaProjection) {
        this.url = url;
        this.mediaProjection = mediaProjection;
        start();
    }

    public void stopLive() {
        videoCodec.stopLive();
        isLiving = false;
    }

    private VideoCodec videoCodec;

    @Override
    public void run() {
        isLiving = true;
        if (!connect(url)) {
            Log.i("fengweijie", "run: ------------->推送失败");
        }
        videoCodec = new VideoCodec(this);
        videoCodec.startLive(mediaProjection);
//        AudioCodec audioCodec = new AudioCodec(this);
//        audioCodec.startLive();
        while (isLiving) {
            RTMPPackage rtmpPackage = null;
            try {
                rtmpPackage = queue.take();
                Log.i("fengweijie", "取出数据");
                if (rtmpPackage.getBuffer() != null && rtmpPackage.getBuffer().length != 0) {
                    Log.i("fengweijie", "run: --------------->推送" + rtmpPackage.getBuffer().length);
                    sendData(rtmpPackage.getBuffer(), rtmpPackage.getBuffer().length,
                            rtmpPackage.getTms(), rtmpPackage.getType());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();

            }

        }
    }
}
